package site.zsxeee.work.spring.oa.controller

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import site.zsxeee.work.spring.oa.database.entity.Dept
import site.zsxeee.work.spring.oa.database.repository.DeptRepository
import site.zsxeee.work.spring.oa.util.AlertInfo
import site.zsxeee.work.spring.oa.util.MVFactory
import javax.servlet.http.HttpServletResponse

@Controller
class DeptsController {
    @Autowired
    private lateinit var deptRepository: DeptRepository

    @RequestMapping("/depts")
    fun getDepts(
            @RequestParam status: String?,
            @RequestParam action: String?
    ) = MVFactory()
            .setTargetViewName("depts")
            .setPageTitle("职位管理")
            .addObject("deptList", deptRepository.findAll())
            .addObject("initTable", true)
            .apply {
                if (status != null) {
                    setAlert(AlertInfo(
                            when (status) {
                                "success" -> AlertInfo.AlertLevel.SUCCESS
                                else -> AlertInfo.AlertLevel.ERROR
                            },
                            when(action){
                                "add"->"添加"
                                "edit"->"修改"
                                "del"->"删除"
                                else->"操作"
                            } + when (status) {
                                "success" -> "成功"
                                else -> "失败"
                            }
                    ))
                }
            }
            .make()

    @RequestMapping("/depts/add", method = [RequestMethod.POST])
    fun addDept(@RequestParam name: String, @RequestParam comment: String, response: HttpServletResponse) {
        try {
            deptRepository.save(Dept().also {
                it.name = name
                it.comment = comment
            })
        } catch (e: Exception) {
            response.sendRedirect("/depts?status=fail&action=add")
        }
        response.sendRedirect("/depts?status=success&action=add")
    }

    @RequestMapping("/depts/del", method = [RequestMethod.GET])
    fun delDept(@RequestParam id: Long, response: HttpServletResponse) {
        try {
            deptRepository.deleteById(id)
        } catch (e: Exception) {
            response.sendRedirect("/depts?status=fail&action=del")
        }
        response.sendRedirect("/depts?status=success&action=del")
    }
}